/*
 *  Copyright 2011 yura.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package org.opu.queryhandler.n.client.ui.actions;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import org.opu.queryhandler.n.client.services.ConnectionService;
import org.opu.queryhandler.n.client.services.DatabaseService;
import org.opu.queryhandler.n.client.services.DriverService;
import org.opu.queryhandler.n.client.services.beans.DataSource;
import org.opu.queryhandler.n.client.services.beans.DriverDefenition;
import org.opu.queryhandler.n.client.ui.actions.db.DbAction;
import org.opu.queryhandler.n.client.ui.widgets.ConnectionDialog;
import org.opu.queryhandler.n.util.GUIUtils;
import org.opu.queryhandler.n.util.Options;
import org.opu.queryhandler.n.util.Options.Option;

/**
 *
 * @author yura
 */
public class DbConnect  extends AbstractAction{
    /** My name */
    public static final String MNAME = "DbConnect";
    private final DatabaseService dbService;
    private final DriverService driverService;
    private final ConnectionService connectionService;
    private final Map<String, DbAction> connectActions;

    public DbConnect(DatabaseService dbService, DriverService driverService,
            ConnectionService connectionService, Map<String, DbAction> actions) {
        this.dbService = dbService;
        this.driverService = driverService;
        this.connectionService = connectionService;
        this.connectActions = actions;
    }

    @Override
    public String getName() {
        return MNAME;
    }

    @Override
    public void action(ActionEvent e) throws Exception{
        try {
            Collection<DataSource> list = null;
            try {
                list = connectionService.getSavedDataSource();
            } catch (IOException ex) {
                logger.error(this, ex);
                Options.error(ex);
                list = Collections.emptyList();
            }

            if (list.isEmpty()) {
                newConnection();
            } else {
                chouseConnection(list);
            }
        } finally {
            for (DbAction a : connectActions.values()) {
                a.reloadData();
            }
        }
    }

    private void newConnection() {
        final ConnectionDialog dialog = new ConnectionDialog(driverService);
        dialog.getOkBtn().setAction(GUIUtils.getAction("Ok", new GUIUtils.ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) throws Exception {
                dbService.initDbManager(dialog.getUrl().getText(), 
                        dialog.getUser().getText(),
                        dialog.getPasswordTf().getText(),
                        (DriverDefenition) dialog.getDrivers().getSelectedItem());

                String str;
                if(Options.choise(getTextResource("storeConnection")) &&
                        (str = Options.select(getTextResource("enterDescription"))) != null) {
                    try {
                        connectionService.addDataSource(new DataSource(
                                dialog.getUrl().getText(),
                                dialog.getUser().getText(),
                                dialog.getPasswordTf().getText(),
                                (DriverDefenition) dialog.getDrivers().getSelectedItem(),
                                str));
                    } catch (IOException ex) {
                        logger.error(this, ex);
                        Options.error(ex);
                    }
                }

                dialog.dispose();
            }
        }));
        dialog.getCancelBtn().setAction(GUIUtils.getAction("Cancel", new GUIUtils.ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        }));
        dialog.resize();
        logger.debug(this, "Show dialog");
        dialog.setVisible(true);
    }

    private void chouseConnection(Collection<DataSource> list) throws Exception {
        Option choise = Options.choise(getTextResource("selectConnection"), list);
        switch (choise.code){
            case Options.CH_CANCEL_OPTION:
                break;
            case Options.CH_NEW_OPTION:
                update(list);
                newConnection();
                break;
            case Options.CH_OK_OPTION:
                update(list);
                dbService.initDbManager((DataSource) choise.source);
                break;
        }
    }

    private void update(Collection<DataSource> list) {
        try {
            connectionService.updeteDataSource(list);
        } catch (IOException ex) {
            logger.error(this, ex);
            Options.error(ex);
        }
    }

}
